package com.mtyee.collection;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_TAKE_PHOTO = 1;
    private Uri photoURI;
    private File image;
    private ImageView imageView;
    private Button upload;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button tackPic = findViewById(R.id.tackPic);   //拍照按钮
        upload = findViewById(R.id.upload);     //上传按钮
        imageView = findViewById(R.id.picture); //图片框ImagView
        progressDialog = new ProgressDialog(this);  //上传的时候弹出的进度提示

        upload.setEnabled(false);       //imageView没有图片的时候设置上传按钮不可用
        tackPic.setOnClickListener(view -> dispatchTakePictureIntent());    //拍照按钮点击监听器
        upload.setOnClickListener(new View.OnClickListener() {              //上传按钮点击监听器
            @Override
            public void onClick(View view) {
                String url = "http://192.168.1.102:8080/image/upload";
                System.out.println(image);
                String path = image.getPath();
                imageUpload(url, path, this);

            }
        });
    }

    //Google官方提供的调用系统相机的方法，我们只做拍照后数据的储存处理
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                // Error occurred while creating the File
                e.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "com.mtyee.collection.fileProvider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    //onActivityResult作为拍照后返回MainActivity的结果处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            imageView.setImageURI(photoURI);
        }
        upload.setEnabled(true);
    }

    //创建一个文件，并用时间日期作为文件名，避免文件重复
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        this.image = image;
        return image;
    }

    // 通过OkHttp框架将图片上传到服务器
    private void imageUpload(String url, String path, final View.OnClickListener context) {
        OkHttpClient mClient = new OkHttpClient();
        File file = new File(path);
        // 构建 MultipartBody
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                        "file",
                        file.getName(),
                        RequestBody.create(MediaType.parse("image/jpg"), file)
                );
        //使用 MultipartBody 构建 RequestBody
        RequestBody requestBody = builder.build();
        // 传入 RequestBody
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = mClient.newCall(request);
        progressDialog.setMessage("上传中");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();

        //OkHttp请求后的结果回调
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.e("upload image", "上传成功:" + response.body().string());
                Looper.prepare();       //创建消息队列 否者空指针报错
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                Looper.loop();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("upload image", "上传失败:" + e.getMessage());
                Looper.prepare();
                Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                Looper.loop();
            }
        });
    }

}